package com.group.seckill.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.group.common.to.SeckillOrderTo;
import com.group.common.to.UserTo;
import com.group.common.utils.R;
import com.group.seckill.feign.ActivityFeignService;
import com.group.seckill.feign.AdminFeignService;
import com.group.seckill.interceptor.LoginUserInterceptor;
import com.group.seckill.service.SeckillService;
import com.group.seckill.to.SeckillSkuRedisTo;
import com.group.seckill.vo.SecondKillConfigurationVo;
import com.group.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author lins
 * @date 2021/11/15 8:56
 */
@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ActivityFeignService activityFeignService;
    @Autowired
    AdminFeignService adminFeignService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    //region redis键前缀
    public static final String SECKILL_SESSION_PREFIX = "seckill:session:";
    public static final String SECKILL_SESSION_SKU_PREFIX = "seckill:skus";
    public static final String SECKILL_STOCK_PREFIX = "seckill:stock:";
    //endregion

    //region 秒杀商品上架
    @Override
    public void uploadSeckillSession() {
        //获取最近三天的秒杀场次和商品信息
        R r = activityFeignService.getSeckillLasted3DaysInfo();
        log.info(JSON.toJSONString(r));
        if (r.getCode() == 0) {
            List<SecondKillConfigurationVo> data = r.getData(new TypeReference<List<SecondKillConfigurationVo>>() {
            });
            //缓存session信息  key为seckill:session:starttime_endtime
            saveSeckillSessionInfo(data);
            //缓存秒杀商品信息
            saveSeckillSessionSkuRelation(data);
        }
    }
    //endregion

    //region 获取当前时间可秒杀的商品信息
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
            //获取当前时间  所在的活动场次
            long now = new Date().getTime();
            Set<String> keys = redisTemplate.keys(SECKILL_SESSION_PREFIX + "*");
            if (keys != null && keys.size() > 0) {
                for (String key : keys) {
                    String[] s = key.substring(key.lastIndexOf(":") + 1).split("_");
                    long start = Long.parseLong(s[0]);
                    long end = Long.parseLong(s[1]);
                    if (now >= start && now <= end) {
                        //查询该场次的所有秒杀商品信息
                        List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                        if (range != null && range.size() > 0) {
                            BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_SESSION_SKU_PREFIX);
                            List<String> list = hashOps.multiGet(range);
                            if (list != null && list.size() > 0) {
                                return list.stream().map(item -> {
                                    SeckillSkuRedisTo redisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                                    redisTo.setRandomCode(null);
                                    return redisTo;
                                }).collect(Collectors.toList());
                            }
                        }
                    }
                }
            }
        return null;
    }
    //endregion

    //region 获取当前商品的商品详情
    @Override
    public SeckillSkuRedisTo getSkuInfoBySkuId(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_SESSION_SKU_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                String regex = "\\d_" + skuId;
                if (Pattern.matches(regex, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    if (redisTo != null) {
                        long now = new Date().getTime();
                        System.out.println(new Date(now));
                        System.out.println(redisTo.getStartTime());
                        System.out.println(redisTo.getEndTime());
                        if (now >= redisTo.getStartTime().getTime() && now <= redisTo.getEndTime().getTime()) {
                            return redisTo;
                        } else {
                            redisTo.setRandomCode(null);
                            return redisTo;
                        }
                    }
                }
            }
        }

        return null;
    }
    //endregion

    //region 秒杀方法
    @Override
    public String seckill(String killId, String key, Integer num) {
        UserTo userTo = LoginUserInterceptor.userTo.get();
        //获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_SESSION_SKU_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)){
            return null;
        }else {
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //验证时间合法性
            long now = new Date().getTime();
            if (now < redisTo.getStartTime().getTime() || now > redisTo.getEndTime().getTime()) {
                return null;
            }else {
                //验证随机码和killId
                String randomCode = redisTo.getRandomCode();
                String kill = redisTo.getSeckillSessionId() + "_" + redisTo.getSkuId();
                if (randomCode.equals(key) && kill.equals(killId)) {
                    //校验数量是否合理
                    if (num <= redisTo.getSeckillLimit()) {
                        //校验这个登陆人是否已经秒杀过这个商品
                        String userKilledKey = userTo.getUserId() +"_" + kill;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(userKilledKey, num.toString());
                        if (aBoolean){
                            //获取信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_STOCK_PREFIX + redisTo.getRandomCode());
                            try {
                                boolean b = semaphore.tryAcquire(num,10, TimeUnit.MILLISECONDS);
                                if (b){
                                    //发送消息给mq,异步处理订单服务
                                    SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                    seckillOrderTo.setOrderBuyersId(userTo.getUserId());
                                    seckillOrderTo.setOrderNumber(num);
                                    seckillOrderTo.setOrderPayPrice(redisTo.getSeckillPrice().multiply(new BigDecimal(num)).toString());
                                    String orderSn = IdWorker.getTimeId();
                                    seckillOrderTo.setOrderSn(orderSn);
                                    seckillOrderTo.setSkuId(redisTo.getSkuId().intValue());
                                    rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.create", seckillOrderTo, new CorrelationData(UUID.randomUUID().toString()));
                                    return orderSn;
                                }
                            } catch (InterruptedException e) {
                                return null;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }
    //endregion

    //region 缓存秒杀场次商品信息
    private void saveSeckillSessionSkuRelation(List<SecondKillConfigurationVo> data) {
        if (data != null) {
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SECKILL_SESSION_SKU_PREFIX);
            data.forEach(secondKillConfigurationVo -> {
                secondKillConfigurationVo.getSeckillSkuRelationshipEntities().forEach(seckillSkuRelationshipVo -> {
                    String randomCode = UUID.randomUUID().toString().replaceAll("-", "");
                    if (!hashOps.hasKey(seckillSkuRelationshipVo.getSeckillSessionId().toString() + "_" + seckillSkuRelationshipVo.getSkuId().toString())) {
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        //远程查询当前skuid对应的商品信息
                        R r = adminFeignService.getSkuInfoBySkuId(seckillSkuRelationshipVo.getSkuId().intValue());
                        if (r.getCode() == 0) {
                            SkuInfoVo skuInfoVo = r.getData(new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfoVo(skuInfoVo);
                        }
                        //设置秒杀信息
                        BeanUtils.copyProperties(seckillSkuRelationshipVo, redisTo);
                        //设置当前商品秒杀时间信息
                        redisTo.setStartTime(secondKillConfigurationVo.getStartTime());
                        redisTo.setEndTime(secondKillConfigurationVo.getEndTime());
                        //商品的随机码
                        redisTo.setRandomCode(randomCode);
                        //当前商品的库存作为信号量存入redis
                        RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_STOCK_PREFIX + randomCode);
                        semaphore.trySetPermits(seckillSkuRelationshipVo.getSeckillCount());
                        //存入redis中
                        String json = JSON.toJSONString(redisTo);
                        hashOps.put(seckillSkuRelationshipVo.getSeckillSessionId().toString() + "_" + seckillSkuRelationshipVo.getSkuId().toString(), json);
                    }
                });
            });
        }
    }
    //endregion

    //region 缓存场次信息
    private void saveSeckillSessionInfo(List<SecondKillConfigurationVo> data) {
        if (data != null) {
            data.forEach(item -> {
                long start = item.getStartTime().getTime();
                long end = item.getEndTime().getTime();
                String key = SECKILL_SESSION_PREFIX + start + "_" + end;
                if (!redisTemplate.hasKey(key)) {
                    List<String> skuIds = item.getSeckillSkuRelationshipEntities().stream().map(seckillSkuRelationshipVo -> {
                        return seckillSkuRelationshipVo.getId() + "_" + seckillSkuRelationshipVo.getSkuId();
                    }).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, skuIds);
                }
            });
        }
    }
    //endregion
}
